package bubuntux.jusbscan.core.antivirus;

import org.apache.commons.lang.StringUtils;

import bubuntux.jusbscan.core.Antivirus;
import bubuntux.jusbscan.core.Configs;
import bubuntux.util.StringUtil;

public class ClamAv extends Antivirus {

	protected static final String SCANNING = "Scanning";
	protected static final String OK = "OK";
	protected static final String EXCLUDED = "Excluded";
	protected static final String FOUND = "FOUND";
	protected static final String EMPTY_FILE = "Empty file";

	public ClamAv() {
		super("clamscan", "-v", "-r", "--remove=yes", "--max-filesize="
				+ Configs.maxFileSize, "--max-dir-recursion="
				+ Configs.maxDirRecursion);
		if (Configs.exclude != null) {
			addParameter("--exclude=" + Configs.exclude);
		}
	}

	@Override
	public boolean finish() {
		boolean finish = false;
		if (this.lastLine == null) {
			finish = true;
		}
		return finish;
	}

	@Override
	public String getActualFile() {
		String message = null;
		if (this.lastLine != null && this.lastLine.startsWith(SCANNING)) {
			message = StringUtil.removeAccents(this.lastLine);
			message = StringUtil.getName(message);
			message = SCANNING + " " + message;
		}
		return message;
	}

	@Override
	public String getVirusFiles() {
		String virus = null;
		if (this.penultimateLine != null
				&& this.penultimateLine.startsWith(SCANNING) == false) {
			boolean include = false;
			if (this.penultimateLine.endsWith(OK)) {
				if (Configs.showOK) {
					include = true;
				}
			} else if (this.penultimateLine.endsWith(EXCLUDED)) {
				if (Configs.showExcluded) {
					include = true;
				}
			} else if (this.penultimateLine.endsWith(EMPTY_FILE)) {
				if (Configs.showEmptyFiles) {
					include = true;
					Configs.beep();
				}
			} else if (this.penultimateLine.endsWith(FOUND)) {
				if (Configs.showInfected) {
					include = true;
					Configs.beep();
				}
			} else {
				if (Configs.showOthers) {
					include = true;
					Configs.beep();
				}
			}
			if (include) {
				virus = StringUtil.removeAccents(this.penultimateLine);
				virus = StringUtil.getName(virus);
			}
		}
		return virus;
	}

	@Override
	public boolean isNewFile() {
		String compare = null;
		if (StringUtils.isNotBlank(this.lastLine)) {
			if (this.lastLine.startsWith(SCANNING)) {
				compare = this.lastLine.substring(SCANNING.length());
			} else if (this.lastLine.lastIndexOf(':') > 0) {
				compare = this.lastLine.substring(0,
						this.lastLine.lastIndexOf(':'));
			}
		}
		return !StringUtils.contains(this.penultimateLine, compare);

	}

	@Override
	public void update() {

		// TODO Auto-generated method stub

	}

}
